package com.ruoyi.procurementmanagement.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.procurementmanagement.domain.ErpGoods;
import com.ruoyi.procurementmanagement.service.IErpGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 商品Controller
 *
 * @author ruoyi
 * @date 2025-03-12
 */
@RestController
@RequestMapping("/procurementmanagement/goods")
public class ErpGoodsController extends BaseController {
    @Autowired
    private IErpGoodsService erpGoodsService;

    /**
     * 查询商品列表
     */
    /**
     * 查询商品列表
     */
    @PreAuthorize("@ss.hasPermi('procurementmanagement:goods:list')")
    @GetMapping("/list")
    public TableDataInfo list(ErpGoods erpGoods) {
        startPage();  // 使用BaseController的分页方法
        List<ErpGoods> list = erpGoodsService.selectErpGoodsList(erpGoods);
        return getDataTable(list);  // 使用BaseController的封装方法
    }



    /**
     * 导出商品列表
     */
    @PreAuthorize("@ss.hasPermi('procurementmanagement:goods:export')")
    @Log(title = "商品", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ErpGoods erpGoods) {
        List<ErpGoods> list = erpGoodsService.selectErpGoodsList(erpGoods);
        ExcelUtil<ErpGoods> util = new ExcelUtil<>(ErpGoods.class);
        util.exportExcel(response, list, "商品数据");
    }

    /**
     * 获取商品详细信息
     */
    @PreAuthorize("@ss.hasPermi('procurementmanagement:goods:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(erpGoodsService.selectErpGoodsById(id));
    }

    /**
     * 新增商品
     */
    @PreAuthorize("@ss.hasPermi('procurementmanagement:goods:add')")
    @Log(title = "商品", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ErpGoods erpGoods) {
        try {
            // 生成唯一编号
            String sn = "G" + new SimpleDateFormat("yyyyMMdd").format(new Date())
                    + String.format("%04d", erpGoodsService.getTodayGoodsCount() + 1);
            erpGoods.setSn(sn);

            // 插入并返回完整对象
            ErpGoods savedGoods = erpGoodsService.insertErpGoods(erpGoods);

            // 确保返回的数据结构包含id
            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("msg", "商品保存成功");
            result.put("data", savedGoods); // 这里包含id

            return AjaxResult.success(result);

        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 修改商品
     */
    @PreAuthorize("@ss.hasPermi('procurementmanagement:goods:edit')")
    @Log(title = "商品", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ErpGoods erpGoods) {
        return toAjax(erpGoodsService.updateErpGoods(erpGoods));
    }

    /**
     * 删除商品
     */
    @PreAuthorize("@ss.hasPermi('procurementmanagement:goods:remove')")
    @Log(title = "商品", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        return toAjax(erpGoodsService.deleteErpGoodsById(id));
    }

    @PreAuthorize("@ss.hasPermi('procurementmanagement:goods:remove')")
    @Log(title = "商品", businessType = BusinessType.DELETE)
    @DeleteMapping("/batch/{ids}")
    public AjaxResult batchRemove(@PathVariable Long[] ids) {
        return toAjax(erpGoodsService.deleteErpGoodsByIds(ids));
    }

    /**
     * 获取商品列表（供前端选择商品时使用）
     */
    @GetMapping("/select-list")
    public AjaxResult selectList() {
        List<ErpGoods> list = erpGoodsService.selectErpGoodsList(null);
        return AjaxResult.success(list);
    }

}
